import re
import subprocess


def get_app_name(package_name, debug=False):
    """获取Android应用的显示名称，支持多模式匹配和调试输出"""
    try:
        # 执行ADB命令获取应用信息
        result = subprocess.check_output(
            f"adb shell dumpsys package {package_name}",
            shell=True
        ).decode("utf-8")

        if debug:
            print(f"[DEBUG] 应用 {package_name} 的 dumpsys 输出长度: {len(result)}")

        # 存储所有可能的匹配模式及其结果
        match_patterns = {
            # 高优先级模式（精确匹配）
            "label_res_id": {
                "pattern": r'labelRes=0x([0-9a-f]+)',
                "processor": lambda m: _process_label_res_id(m, result)
            },
            "application_label": {
                "pattern": r'application: label="(.+?)"',
                "processor": lambda m: m.group(1)
            },
            "non_localized_label": {
                "pattern": r'nonLocalizedLabel="(.+?)"',
                "processor": lambda m: m.group(1)
            },
            # 中等优先级模式（引号不同）
            "application_label_single_quote": {
                "pattern": r"application: label='(.+?)'",
                "processor": lambda m: m.group(1)
            },
            "non_localized_label_single_quote": {
                "pattern": r"nonLocalizedLabel='(.+?)'",
                "processor": lambda m: m.group(1)
            },
            # 低优先级模式（通用匹配）
            "generic_label": {
                "pattern": r'label="(.+?)"',
                "processor": lambda m: m.group(1)
            },
            "generic_label_single_quote": {
                "pattern": r"label='(.+?)'",
                "processor": lambda m: m.group(1)
            },
            # 备选模式（使用进程名或包名）
            "process_name": {
                "pattern": r'processName="(.+?)"',
                "processor": lambda m: m.group(1)
            },
            "package_name_fallback": {
                "pattern": r'Package \[(.+?)\]',
                "processor": lambda m: m.group(1)
            }
        }

        # 按优先级尝试匹配
        for pattern_name, pattern_info in match_patterns.items():
            match = re.search(pattern_info["pattern"], result)
            if match:
                app_name = pattern_info["processor"](match)
                if debug:
                    print(f"[DEBUG] 匹配成功: {pattern_name}, 应用名称: {app_name}")
                return app_name

        # 特殊情况：尝试从ResourceMap中提取
        resource_map_match = re.search(r'ResourceMap\[(.+?)\]', result)
        if resource_map_match:
            possible_name = resource_map_match.group(1).split('/')[-1]
            if debug:
                print(f"[DEBUG] 从ResourceMap提取: {possible_name}")
            return possible_name

        if debug:
            print("[DEBUG] 所有匹配模式均失败")
            # 输出部分关键内容用于调试
            print("[DEBUG] 关键内容片段:")
            for line in result.split('\n'):
                if 'label' in line.lower() or package_name in line:
                    print(f"[DEBUG]   {line.strip()}")

        return "未找到应用名称"

    except subprocess.CalledProcessError as e:
        return f"ADB命令执行失败: {e}"
    except Exception as e:
        return f"错误: {str(e)}"


def _process_label_res_id(match, dumpsys_output):
    """处理labelRes资源ID，尝试从dumpsys输出中找到对应的字符串"""
    label_res_id = match.group(1)
    # 尝试通过 resLabel 字段获取实际标签
    res_label_match = re.search(rf'resLabel\(0x{label_res_id}\)=([^\n]+)', dumpsys_output)
    if res_label_match:
        return res_label_match.group(1).strip()

    # 尝试从资源表中提取
    resource_table_pattern = rf'0x{label_res_id}\s+([^\n]+)'
    resource_match = re.search(resource_table_pattern, dumpsys_output)
    if resource_match:
        return resource_match.group(1).strip().split(' ')[-1]

    return f"资源ID:0x{label_res_id}"


# 示例使用
if __name__ == "__main__":
    # 启用调试模式查看详细匹配过程
    print(get_app_name("com.baidu.tieba", debug=True))